import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/*这道题一定要重新做
* 官方解题更好*/
public class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];  /*返回负数*/
            }
        });
        int len = intervals.length;
        int i = 0;
        ArrayList<int[]> list = new ArrayList<>();
        while (i < len) {
            int left = intervals[i][0];
            while (i < len - 1 || intervals[i+1][1] <= intervals[i][0]){
                i++;
            }
            int right = intervals[i][1];
            int[] temp = new int[2];
            temp[0] = left;
            temp[1] = right;
            list.add(temp);
            i++;
        }
        return ArrayList.toArray;
    }
}

/*上面写的代码还是有很多问题的
* 1；思路不清晰有错误
* 2.*/
class Solution2 {
    public int[][] merge(int[][] intervals) {
        if (intervals.length == 0) {
            return new int[0][2];
        }
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];  /*返回负数*/
            }
        });
        int len = intervals.length;
        ArrayList<int[]> list = new ArrayList<>();
        int left = intervals[0][0], right = intervals[0][0];
        for (int i = 0; i < len; i++) {

                if (right < intervals[i][0]) {
                    list.add(new int[]{left, right});
                    if (i + 1 < len-1) {
                        left = intervals[i + 1][0];
                        right = intervals[i + 1][0];
                    } else {
                        left = intervals[i + 1][0];
                        right = intervals[i+1][1];
                        list.add(new int[]{left, right});
                        return list.toArray(new int[list.size()][]);
                    }
                } else {

                    right = Math.max(intervals[i][1], right);
                }

        }
        return list.toArray(new int[list.size()][]);  // 注意合理返回数组的用法
    }
}

